package kr.nextree.edu.opendic.wizards;

import java.util.Iterator;

import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.Path;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.wizard.WizardPage;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.FileDialog;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Text;

import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;

public class SelectFilesWizardPage extends WizardPage {

    private Text sourceFileField;
    private Text destinationFileField;
    private IPath initialSourcePath;

    public SelectFilesWizardPage() {
        super("selectFiles");
        setTitle("Select files");
        setDescription("Select the Source and destination files");
    }

    @Override
    public void createControl(Composite parent) {
        Composite composite = new Composite(parent, SWT.NONE);
        GridLayout gridLayout = new GridLayout();
        gridLayout.numColumns = 3;
        composite.setLayout(gridLayout);
        setControl(composite);

        Label lb = new Label(composite, SWT.NONE);
        GridData gridData = new GridData();
        gridData.horizontalSpan = 3;
        lb.setLayoutData(gridData);
        lb.setText("Select the Plugin.xml file from which stirngs will be extracted.");

        lb = new Label(composite, SWT.NONE);
        gridData = new GridData(GridData.HORIZONTAL_ALIGN_END);
        lb.setLayoutData(gridData);
        lb.setText("SourceFile : ");

        sourceFileField = new Text(composite, SWT.BORDER);
        sourceFileField.addModifyListener(new ModifyListener() {
            @Override
            public void modifyText(ModifyEvent e) {
                updatePageComplete();
            }
        });
        sourceFileField.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));

        Button button = new Button(composite, SWT.NONE);
        button.addSelectionListener(new SelectionAdapter() {
            @Override
            public void widgetSelected(SelectionEvent e) {
                browserForSourceFile();
            }
        });
        button.setText("Browse....");

        lb = new Label(composite, SWT.NONE);
        gridData = new GridData();
        gridData.horizontalSpan = 3;
        lb.setLayoutData(gridData);

        lb = new Label(composite, SWT.NONE);
        gridData = new GridData();
        gridData.horizontalSpan = 3;
        lb.setLayoutData(gridData);
        lb.setText("Select the plugin.properties file into which strings will be replaces.");

        lb = new Label(composite, SWT.NONE);
        gridData = new GridData();
        gridData.horizontalIndent = 20;
        lb.setLayoutData(gridData);
        lb.setText("Destination File : ");

        destinationFileField = new Text(composite, SWT.BORDER);
        destinationFileField.addModifyListener(new ModifyListener() {
            @Override
            public void modifyText(ModifyEvent e) {
                updatePageComplete();
            }
        });
        destinationFileField.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL));
        button = new Button(composite, SWT.NONE);
        button.addSelectionListener(new SelectionAdapter() {
            @Override
            public void widgetSelected(SelectionEvent e) {
                browserForDestinationFile();
            }
        });
        button.setText("Browse....");
        initContents();
    }

    public void init(ISelection selection) {
        if (!(selection instanceof IStructuredSelection)) return;

        @SuppressWarnings("rawtypes")
        Iterator iter = ((IStructuredSelection) selection).iterator();
        while (iter.hasNext()) {
            Object item = (Object) iter.next();
            if (item instanceof IJavaElement) {
                IJavaElement javaElem = (IJavaElement) item;
                try {
                    item = javaElem.getUnderlyingResource();
                }
                catch (JavaModelException e) {
                    e.printStackTrace();
                    continue;
                }
            }
            if (item instanceof IFile) {
                IFile file = (IFile) item;
                if (file.getName().equals("plugin.xml")) {
                    initialSourcePath = file.getLocation();
                    break;
                }
                item = file.getProject();
            }
            if (item instanceof IProject) {
                IFile file = ((IProject) item).getFile("plugin.xml");
                if (file.exists()) {
                    initialSourcePath = file.getLocation();
                    break;
                }
            }
        }
    }

    private void initContents() {
        if (this.initialSourcePath == null) return;
        IPath rootLoc = ResourcesPlugin.getWorkspace().getRoot().getLocation();
        IPath path = initialSourcePath;
        if (rootLoc.isPrefixOf(path)) {
            path = path.setDevice(null).removeFirstSegments(rootLoc.segmentCount());
        }
        sourceFileField.setText(path.toString());
        destinationFileField.setText(path.removeLastSegments(1).append("Plugin.properties").toString());
        updatePageComplete();
        setMessage(null);
        setErrorMessage(null);

    }

    private void updatePageComplete() {
        setPageComplete(false);

        IPath sourceLoc = getSourceLocation();
        if (sourceLoc == null || !sourceLoc.toFile().exists()) {
            setMessage(null);
            setErrorMessage("Please Select an existing plugin.xml file ");
            return;
        }

        IPath destinationLoc = getDestinationLocation();
        if (destinationLoc == null || !destinationLoc.toFile().exists()) {
            setMessage(null);
            setErrorMessage("Please spectify a plugin.properties file to contain the extracted strings ");
            return;
        }

        setPageComplete(true);

        IPath sourceDirPath = sourceLoc.removeLastSegments(1);
        IPath destinationDirPath = destinationLoc.removeLastSegments(1);

        if (!sourceDirPath.equals(destinationDirPath)) {
            setErrorMessage(null);
            setMessage("The Plugin.properties file is typically located it the same directory as the plugin.xml file", WARNING);
            return;
        }
        if (!destinationDirPath.lastSegment().equals("Plugin.properties")) {
            setErrorMessage(null);
            setMessage("The destination file is typically named Plugin.properties", WARNING);
            return;
        }

        setMessage(null);
        setErrorMessage(null);

    }

    public IPath getSourceLocation() {
        String text = sourceFileField.getText().trim();
        if (text.length() == 0) return null;
        IPath path = new Path(text);
        if (!path.isAbsolute()) {
            path = ResourcesPlugin.getWorkspace().getRoot().getLocation().append(path);
        }
        return path;

    }

    public IPath getDestinationLocation() {
        String text = destinationFileField.getText().trim();
        if (text.length() == 0) return null;
        IPath path = new Path(text);
        if (!path.isAbsolute()) {
            path = ResourcesPlugin.getWorkspace().getRoot().getLocation().append(path);
        }
        return path;

    }

    private void browserForSourceFile() {
        IPath path = browse(getSourceLocation(), false);
        if (path == null) return;
        IPath rootLoc = ResourcesPlugin.getWorkspace().getRoot().getLocation();
        if (rootLoc.isPrefixOf(path)) {
            path = path.setDevice(null).removeFirstSegments(rootLoc.segmentCount());
        }
        sourceFileField.setText(path.toString());
    }

    private void browserForDestinationFile() {
        IPath path = browse(getDestinationLocation(), false);
        if (path == null) return;
        IPath rootLoc = ResourcesPlugin.getWorkspace().getRoot().getLocation();
        if (rootLoc.isPrefixOf(path)) {
            path = path.setDevice(null).removeFirstSegments(rootLoc.segmentCount());
        }
        destinationFileField.setText(path.toString());
    }

    private IPath browse(IPath path, boolean mustExist) {
        FileDialog dialog = new FileDialog(getShell(), mustExist ? SWT.OPEN : SWT.SAVE);
        if (path != null) {
            if (path.segmentCount() > 1) {
                dialog.setFilterPath(path.removeLastSegments(1).toOSString());
            }
            if (path.segmentCount() > 0) {
                dialog.setFileName(path.lastSegment());
            }
        }
        String result = dialog.open();
        if (result == null) return null;
        return new Path(result);
    }
}
